import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps, ProFormInstance } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
  ProFormSelect,
  ProForm,
} from '@ant-design/pro-components';
import { Button, Drawer, Form, message, Image, Popconfirm } from 'antd';
import React, { useRef, useState, useEffect, act } from 'react';
import { newPageAdd, newPageRemove, newPageQuery, newPageUpdate } from '@/services/ant-design-pro/home';
import ImageUpload from '@/components/ImageUpload';
import { default as ReactQuill } from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { TableListItem } from '../table-list/data';
import { FormValueType } from '../table-list/components/UpdateForm';

/**
 * 删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await newPageRemove({
      id: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [uploadUrl, setUploadUrl] = useState<string>('');
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const [activeKey, setActiveKey] = useState<string>('1');
  const formRef = useRef<ProFormInstance>();

  const confirm = async (id: number) => {
    await newPageRemove({ id });
    message.success('删除成功');
    actionRef.current?.reloadAndRest?.();
  };

  const handleAdd = async (fields: TableListItem) => {
    const hide = message.loading('正在添加');
    try {
      await newPageAdd({ ...fields, url: uploadUrl, type: activeKey });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
    const hide = message.loading('正在配置');
    try {
      await newPageUpdate({
        ...currentRow,
        ...fields,
        url: uploadUrl,
      });
      hide();
      message.success('配置成功');
      return true;
    } catch (error) {
      hide();
      message.error('配置失败，请重试！');
      return false;
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    
    {
      title: '类型名称',
      dataIndex: 'typeName',
      width: 150,
      search: false,
      ellipsis: true,
      render: (dom, entity) => (
        <a
          onClick={() => {
            setCurrentRow(entity);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(entity.pictureUrl);
          }}
        >
          {dom}
        </a>
      ),
      hidden: true
    },
    {
      title: '内容',
      dataIndex: 'content',
      valueType: 'textarea',
      search: false,
      width: 200,
      hidden: activeKey === '7' ? true : false,
      ellipsis: true,
      render: (dom, entity) => (
        <a
          onClick={() => {
            setCurrentRow(entity);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(entity.pictureUrl);
          }}
        >
          {dom}
        </a>
      ),
      
    },
    {
      width:100,
      title: '跳转链接',
      dataIndex: 'targetUrl',
      hideInForm: true,
      renderText: (val: string) => `${val || ''}`,
      search: false,
      ellipsis: true
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueEnum: {
        1: { text: '天气预报' },
        2: { text: '商业气象合作' },
        3: { text: '气象研究' },
        4: { text: '关于我们' },
        5: { text: '联系我们' },
        6: { text: '网站最底部信息' },
        7: { text: '行业领军客户的选择' },
      },
      hidden: true,
      width: 150,
      search: false,
    },
    {
        title: '图片',
        dataIndex: 'pictureUrl',
        render: (text) => <Image src={text} alt="图片" style={{ width: 90, height: 40 }} />,
        search: false,
        width: 110,
        hidden:  (activeKey === '1' || activeKey === '2' || activeKey === '3' || activeKey === '4'  || activeKey === '6') ? true : false,
      },
      {
        title: '排序',
        dataIndex: 'sort',
        width: 50,
        ellipsis: true,
        search: false
      },
    {
      title: '操作',
      width: 150,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            setIsEditing(true);
            setDrawerVisible(true);
            setUploadUrl(record.pictureUrl);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除吗？"
          onConfirm={() => confirm(record.id)}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const imageUploadPropsMap = {
    // '1': { maxWidth: 1920, maxHeight: 510 },
    // '2': { maxWidth: 1200, maxHeight: 400 },
    // '3': { maxWidth: 1024, maxHeight: 300 },
    // '4': { maxWidth: 800, maxHeight: 200 },
    '5': { maxWidth: 32, maxHeight: 32 },
    '7': { maxWidth: 370, maxHeight: 140 }
  };

  const getImageUploadProps = (activeKey: string) => {
    return imageUploadPropsMap[activeKey] || {};
  };

  useEffect(() => {
    if (drawerVisible && formRef.current) {
      formRef.current.setFieldsValue(currentRow || {});
    }
  }, [drawerVisible, currentRow]);

  return (
    <PageContainer header={{ title: '' }}>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setIsEditing(false);
              setCurrentRow(undefined);
              setDrawerVisible(true);
              setUploadUrl('');
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        toolbar={{
          menu: {
    
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: '1', label: '支持与帮助' },
              { key: '2', label: '商业气息服务' },
              { key: '3', label: '产品' },
              { key: '4', label: '关于' },
              { key: '5', label: '联系我们' },
              { key: '7', label: '行业领军客户的选择' },
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
        request={(params) => newPageQuery({ ...params, type: activeKey })}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <Drawer
        title={isEditing ? "编辑信息" : "新建信息"}
        width={600}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        destroyOnClose
      >
        <ProForm
          layout="vertical"
          formRef={formRef}
          initialValues={currentRow || {}}
          onFinish={async (value) => {
            let success = false;
            if (isEditing) {
              success = await handleUpdate(value, currentRow);
            } else {
              success = await handleAdd(value);
            }

            if (success) {
              setDrawerVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
            label="类型名称"
            name="typeName"
            hidden
          />
          <ProFormText name="content" label="内容" />
          {/* <ProFormTextArea name="content" label="详细内容"> */}
            
          <ProFormSelect
            name="type"
            label="类型"
            options={[
              { label: '天气预报', value: 1 },
              { label: '商业气象合作', value: 2 },
              { label: '气象研究', value: 3 },
              { label: '关于我们', value: 4 },
              { label: '联系我们', value: 5 },
              { label: '网站最底部信息', value: 6 },
              { label: '行业领军客户的选择', value: 7 },
            ]}
            placeholder="请选择类型"
            hidden
          />
          <ProFormText label="链接地址" name="targetUrl" />
          <ProForm.Item
            name="pictureUrl"
            label="图片地址"
            hidden={ (activeKey === '1' || activeKey === '2' || activeKey === '3' || activeKey === '4'  || activeKey === '6') ? true : false}
          >
            <ImageUpload maxWidth={getImageUploadProps(activeKey).maxWidth} maxHeight={getImageUploadProps(activeKey).maxHeight} value={uploadUrl} onChange={(url) => setUploadUrl(url)} />
          </ProForm.Item>
          <ProFormText label="图片alt" name="alt"
          hidden={ (activeKey === '1' || activeKey === '2' || activeKey === '3' || activeKey === '4'  || activeKey === '6') ? true : false}
          ></ProFormText>
           <ProFormText label="排序" name="sort"></ProFormText>
        </ProForm>
      </Drawer>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.typeName && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.typeName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.typeName,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
